package com.example.zhongshuishi.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.example.zhongshuishi.entity.*;
import com.example.zhongshuishi.service.PaymentService;
import com.example.zhongshuishi.service.PersonnelService;
import com.example.zhongshuishi.service.StudentService;
import com.example.zhongshuishi.service.TaxService;
import com.example.zhongshuishi.service.implService.InvoiceServiceImpl;
import com.example.zhongshuishi.taxs_api.RequestKit;
import com.example.zhongshuishi.utils.JwtTokenUtil;
import com.example.zhongshuishi.utils.KSXJWTUtil;
import com.example.zhongshuishi.utils.KSXPostUtil;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.security.Principal;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class ApiController {
    private final InvoiceServiceImpl apiService;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private StudentService studentService;
    @Autowired
    private TaxService taxService;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private PersonnelService personnelService;

    @Autowired
    public ApiController(InvoiceServiceImpl apiService) {
        this.apiService = apiService;
    }


    //人脸识别
    @PostMapping("/identify")
    public ResponseEntity identifyApi(@RequestBody InvoiceDto invoiceDto) throws UnsupportedEncodingException {
        String s = apiService.identifyApi(invoiceDto);
        return ResponseEntity.ok().body(s);
    }

    //开票
    @PostMapping("/invoice")
    public ResponseEntity invoiceApi(@RequestBody  InvoiceDto invoiceDto,@NotNull Integer stuId,@NotNull String orderId) throws UnsupportedEncodingException {
        if(invoiceDto.getFplxdm() == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("fplxdm is null");
        }
        if(invoiceDto.getKplx() == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("kplx is null");
        }
        if(invoiceDto.getTspz() == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("tspz is null");
        }
        if(invoiceDto.getGhdwmc() == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("ghdwmc is null");
        }
        if(invoiceDto.getFphxz() == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("fphxz is null");
        }
        if(invoiceDto.getSpmc() == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("spmc is null");
        }
        if(invoiceDto.getJe() == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("je is null");
        }
        if(invoiceDto.getSl() == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("sl is null");
        }
        if(invoiceDto.getSe() == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("se is null");
        }
        if(invoiceDto.getHsbz() == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("hsbz is null");
        }
        if(invoiceDto.getSpbm() == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("spbm is null");
        }
        if(invoiceDto.getHjje() == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("hjje is null");
        }
        if(invoiceDto.getHjse() == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("hjse is null");
        }
        if(invoiceDto.getJshj() == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("jshj is null");
        }
        if(invoiceDto.getKplx() == "1"){
            if(invoiceDto.getXxbid() == null){
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("xxbid is null");
            }
        }

        //订单校验
        List<PaymentOrder> paymentOrders = paymentService.selectByIdOrderNo(stuId.toString(), orderId, null, null);
        if(paymentOrders  != null && paymentOrders.size() > 0){
            PaymentOrder paymentOrder = paymentOrders.get(0);
            if(paymentOrder != null){
                Integer paymentStatus = paymentOrder.getPaymentStatus();
                if(paymentStatus != 1){
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("订单未支付无法开票");
                }
            }
        }else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("订单未支付无法开票");
        }

        String sid= UUID.randomUUID().toString().replace("-", "");
        invoiceDto.setSid(sid);
        JSONObject jsonObject = apiService.invoiceApi(invoiceDto);
        try{
            //同步数据库
            JSONObject reObj=JSONObject.parseObject(String.valueOf(jsonObject));
            String code = reObj.getString("code");
            if ("00000".equals(code)) {
                JSONObject data = reObj.getJSONObject("data");
                String sid1 = reObj.getString("sid");
                Tax tax = new Tax();
                if(data != null) {
                    String qdfphm = data.getString("qdfphm");
                    String kprq = data.getString("kprq");
                    String ewm_url = data.getString("ewm_url");
                    tax.setQdfphm(qdfphm);
                    tax.setYkprq(kprq);
                    tax.setEwmurl(ewm_url);
                }
                tax.setStuId(stuId);
                tax.setSid(sid1);
                tax.setKplx("0");//蓝票
                List<Tax> taxes = taxService.selectList(tax);
                if(taxes != null && taxes.size() > 0) {
                    Tax tax1 = taxes.get(0);
                    tax.setId(tax1.getId());
                    taxService.updateByPrimaryKeySelective(tax);
                }else {
                    taxService.insertSelective(tax);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseEntity.ok(jsonObject);
    }


    //申请红冲
    @PostMapping("/redPunch")
    public ResponseEntity<?> redPunchApi(@RequestBody InvoiceDto invoiceDto,@NotNull Integer stuId) throws UnsupportedEncodingException {
        if(invoiceDto.getChyydm() == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("chyydm is null");
        }
        if(invoiceDto.getYfphm() == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("yfphm is null");
        }
        if(invoiceDto.getYkprq() == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("ykprq is null");
        }
        String sid= UUID.randomUUID().toString().replace("-", "");
        invoiceDto.setSid(sid);
        JSONObject jsonObject = apiService.redPunchApi(invoiceDto);
        try{
            //同步数据库
            JSONObject reObj=JSONObject.parseObject(String.valueOf(jsonObject));
            String code = reObj.getString("code");
            if ("00000".equals(code)) {
                JSONObject data = reObj.getJSONObject("data");
                String sid1 = reObj.getString("sid");
                Tax tax = new Tax();
                if(data != null) {
                    JSONObject hzfpxx = data.getJSONObject("hzfpxx");
                    if(hzfpxx != null) {
                        String ewmUrl = hzfpxx.getString("ewmUrl");
                        String qdfphm = hzfpxx.getString("qdfphm");
                        String kprq = hzfpxx.getString("kprq");
                        tax.setEwmurl(ewmUrl);
                        tax.setQdfphm(qdfphm);
                        tax.setYkprq(kprq);
                    }
                    String xxbid = data.getString("xxbid");
                    String qrjkpbz = data.getString("qrjkpbz");
                    String hzfpxxqrdZtdm = data.getString("hzfpxxqrdZtdm");
                    tax.setXxbid(xxbid);
                    tax.setQrjkpbz(qrjkpbz);
                    tax.setHzfpxxqrdztdm(hzfpxxqrdZtdm);
                }
                tax.setStuId(stuId);
                tax.setSid(sid1);
                tax.setKplx("1");//红票
                List<Tax> taxes = taxService.selectList(tax);
                if(taxes != null && taxes.size() > 0) {
                    Tax tax1 = taxes.get(0);
                    tax.setId(tax1.getId());
                    taxService.updateByPrimaryKeySelective(tax);
                }else {
                    taxService.insertSelective(tax);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseEntity.ok(jsonObject);
    }



    //通用查询
    @PostMapping("/taxInfo")
    public ResponseEntity<?> taxInfo(@RequestBody InvoiceDto invoiceDto) throws UnsupportedEncodingException {
        if(invoiceDto.getSid() == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("sid is null");
        }
        JSONObject jsonObject = apiService.taxInfo(invoiceDto);
        return ResponseEntity.ok(jsonObject);
    }




    //查询个人信息
    @PostMapping("/selectInformation")
    public List<StudentDto> selectInformation(@RequestBody InvoiceDto invoiceDto)  {
        List<StudentDto> list=apiService.selectInformation(invoiceDto);
        System.out.println(list);
        return list;
    }

    //获取当前登录用户
    @GetMapping("/current/userInfo")
    public CustomerUserDetails currentUserInfo(HttpServletRequest request) {
        try{
            CustomerUserDetails customerUserDetails = new CustomerUserDetails();
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Object principal1 = authentication.getPrincipal();
            if(principal1 instanceof CustomerUserDetails){
                customerUserDetails = (CustomerUserDetails) principal1;
            }else {
                String authHeader = request.getHeader(tokenHeader);
                // 该 JWT 是我们规定的格式，以 tokenHead 开头
                if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
                    // The part after "Bearer "
                    String authToken = authHeader.substring(this.tokenHead.length());
                    // 从 JWT 中获取用户名
                    String phoneJwt = jwtTokenUtil.getPhoneFromToken(authToken);
                    String roleFromToken = jwtTokenUtil.getRoleFromToken(authToken);
                    String idFromToken = jwtTokenUtil.getIdFromToken(authToken);
                    String userNameFromToken = jwtTokenUtil.getUserNameFromToken(authToken);
                    customerUserDetails.setPhone(phoneJwt);
                    customerUserDetails.setRoleFromToken(roleFromToken);
                    customerUserDetails.setId(idFromToken);
                    customerUserDetails.setName(userNameFromToken);
                }
            }
            return customerUserDetails;

        }catch (Exception e ){
            e.printStackTrace();
        }
        return null;
    }

    @PostMapping("/ksx")
    public ResponseEntity<Map<String, Object>> loginKaoShiXing(@RequestBody StudentDto student) {
        try {
            String postUrl = KSXJWTUtil.getPostUrl("201");
            CustomerUserDetails customerUserDetails = new CustomerUserDetails();

            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Object principal1 = authentication.getPrincipal();
            if (principal1 instanceof CustomerUserDetails) {
                customerUserDetails = (CustomerUserDetails) principal1;
            }
            String s = studentService.selectPaymentStatus(customerUserDetails.getId());

            Map<String, Object> params = new HashMap<>();
            params.put("user_id", customerUserDetails.getPhone());
            params.put("user_name", customerUserDetails.getName());
            params.put("department", "中税师/未缴费");


            String response = KSXPostUtil.sendPost(postUrl, params);
            System.out.println("考试星响应: " + response);

            if ("1".equals(s)) {
                String postUrl2 = KSXJWTUtil.getPostUrl("202");

                String jwt = extractJwtFromUrl(postUrl);
                if (jwt != null) {
                    String modifyDepUrl = String.format("https://api.kaoshixing.com/api/company/data/618654/?jwt=%s", jwt);

                    Map<String, Object> modifyParams = new HashMap<>();
                    modifyParams.put("user_id", customerUserDetails.getPhone());
                    modifyParams.put("department", "中税师/已缴费");

                    String modifyResponse = KSXPostUtil.sendPost(postUrl2, modifyParams);
                    System.out.println("修改部门响应: " + modifyResponse);

                    try {
                        JsonObject jsonResponse = JsonParser.parseString(modifyResponse).getAsJsonObject();
                        if (jsonResponse.get("code").getAsInt() != 10000) {
                            System.err.println("部门修改失败: " + jsonResponse.get("msg").getAsString());
                        }
                    } catch (Exception e) {
                        System.err.println("解析修改部门响应异常: " + e.getMessage());
                    }
                }
            }

            if (response != null) {
                JsonObject jsonResponse = JsonParser.parseString(response).getAsJsonObject();
                if (jsonResponse.get("code").getAsInt() == 10000) {
                    String redirectUrl = jsonResponse.get("url").getAsString();

                    if (!redirectUrl.startsWith("http")) {
                        redirectUrl = "https://" + redirectUrl;
                    }

                    Map<String, Object> result = new HashMap<>();
                    result.put("url", redirectUrl);
                    return ResponseEntity.ok(result);
                }
            }

            Map<String, Object> error = new HashMap<>();
            error.put("error", "无法获取考试星登录地址");
            return ResponseEntity.status(500).body(error);

        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> error = new HashMap<>();
            error.put("error", "系统异常: " + e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }


    private String extractJwtFromUrl(String url) {
        try {
            URI uri = new URI(url);
            String query = uri.getQuery();
            if (query != null) {
                String[] params = query.split("&");
                for (String param : params) {
                    if (param.startsWith("jwt=")) {
                        return param.split("=")[1];
                    }
                }
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return null;
    }


    // 2. 导出控制器,teacherId 不传查所有学生
    @GetMapping("/student/export")
    public void exportStudentExcel(HttpServletResponse response,Integer teacherId) throws IOException {
        // 设置响应头（解决中文乱码）
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode("学生列表数据.xlsx", "UTF-8"));

        // 3. 准备数据（动态添加序号）
        List<StudentDto> studentDtos = studentService.selectByPersonnal(teacherId, null, null, null, null, null, null, null);
        // 4. 执行导出
        EasyExcel.write(response.getOutputStream(), StudentDto.class)
                .sheet("用户列表")
                .doWrite(studentDtos);
    }

    // 2. 导出控制器,parentId 不传查所有代理人
    @GetMapping("/personal/export")
    public void exportPersonalExcel(HttpServletResponse response,Integer parentId) throws IOException {
        // 设置响应头（解决中文乱码）
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode("老师列表数据.xlsx", "UTF-8"));

        // 3. 准备数据（动态添加序号）
        List<PersonnelDto> personnelDtos = personnelService.selectByParentId(parentId);
        personnelDtos.stream().map(item ->{
            if("1".equals(item.getDeleflag())){
                item.setDeleflag("是");
            }else {
                item.setDeleflag("否");
            }
            if(item.getPersonLevel()==1){
                item.setPersonLevelName("总代理");
            }
            if(item.getPersonLevel()==2){
                item.setPersonLevelName("省代理");
            }
            if(item.getPersonLevel()==3){
                item.setPersonLevelName("市代理");
            }
            return item;
        }).collect(Collectors.toList());
        // 4. 执行导出
        EasyExcel.write(response.getOutputStream(), PersonnelDto.class)
                .sheet("老师列表")
                .doWrite(personnelDtos);
    }

}